package com.wanghlme.exercise05.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

@WebFilter(
        urlPatterns = "/*",
        initParams = {
                @WebInitParam(name = "encode", value = "utf-8")
        }
)
public class CharacterEncodingFilter implements Filter {
    private String encode = "utf-8";

    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println("startup filter");
        encode = config.getInitParameter("encode");
    }

    @Override
    public void destroy() {
        System.out.println("destroy filter");
        Filter.super.destroy();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        request.setCharacterEncoding(encode);
        response.setCharacterEncoding(encode);
        response.setContentType("text/html;charset=UTF-8");
        System.out.println("do filter");
        chain.doFilter(request, response);
    }
}
